package com.asap.demo.ck.util;

import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @ClassName: FuncStatic   
 * @Description: TODO  
 * @author: suyb@asiainfo-sec.com   
 * @date:2018年3月9日 上午10:13:35
 */
public final class FuncStatic {
	
	private FuncStatic() {}

	/**
	 * @Title: errorTrace   
	 * @Description: 异常输出  
	 * @param e 异常
	 * @return String  
	 * @throws
	 */
	public static String errorTrace(Exception e){
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		e.printStackTrace(pw);  
		return sw.toString();
 	}
	
	/**
	 * @Title: checkIsEmpty   
	 * @Description: 判断是否为空  
	 * @param var 判别对象
	 * @return boolean  
	 * @throws
	 */
	public static boolean checkIsEmpty(Object var) {
		if (var == null) {
			return true;
		}
		if (var.toString().equals("")) {
			return true;
		}
		return false;
	}
	
	/**
	 * 去掉一个字符串两端的某个字符串
	 * @param str
	 *            原字符串
	 * @param c
	 *            需要去掉的字符串
	 * @return 返回
	 */
	public static String trim(String str, String c) {
		while (str.startsWith(c)) {
			str = str.substring(c.length(), str.length());
		}
		while (str.endsWith(c)) {
			str = str.substring(0, str.length() - c.length());
		}
		return str;
	}
	
	/**
	 * 正则表达式搜索字符串
	 * 
	 * @param str 搜索父体
	 * @param reg 正则
	 * @return 命中的词
	 */
	public static String searchString(String str, String reg) {
		Pattern p = Pattern.compile(reg);
		Matcher m = p.matcher(str);
		if (m.find()) {
			return m.group(1);
		}
		return "";
	}
	
	/**
	 * @Title: getFieldValue   
	 * @Description: TODO 从json字符串中提取属性值  
	 * @param  json json对象
	 * @param  filedName 属性名
	 * @return String 属性值
	 * @throws
	 */
	/*
	public static String getJsonFieldValue(String json,String filedName) {
		JsonElement je = new com.google.gson.JsonParser().parse(json);
		JsonElement jsonElement = je.getAsJsonObject().get(filedName);
		if(jsonElement != null) {
			return jsonElement.getAsString();
		}
		return null;
	}
	*/
	/**
	 * valid parameter
	 * @param parameter parameter
	 * @return boolean
	 */
	public static boolean isNotNull(Object  parameter)  {
		if (parameter == null) {
			return false;
		}
		if (String.valueOf(parameter).isEmpty()) {
			return false;
		}
		return  true;
	}
	public static String jasyptEncode(String algorithm,String salt,String passwd){
		StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
		encryptor.setAlgorithm(algorithm);
        encryptor.setPassword(salt);
        String encPasswd=encryptor.encrypt(passwd);
        return encPasswd;
	}
	public static String jasyptDecode(String algorithm,String salt,String passwd){
		StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
		encryptor.setAlgorithm(algorithm);
        encryptor.setPassword(salt);
        String decPasswd=encryptor.decrypt(passwd);
        return decPasswd;
	}
}
